<template>
  <div class="info-box">
    <el-row class=" b-f header">
      <el-page-header @back="goBack" :content="title">
      </el-page-header>
      <span class="saveBtn" v-if="isAudit">
        <el-button type="primary" @click="auditMethed">审核通过</el-button>
        <el-button type="primary" plain @click="auditNoMethed">审核不通过</el-button>
      </span>
      <span class="saveBtn" v-if="!isAudit&&isFlag !== 'look'">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button type="primary" plain @click="goBack">取消</el-button>
      </span>
    </el-row>
    <div class="p-d form-content">
      <div class="p-d b-f">
        <el-row class="p-b">
          <h1 class="before">基本信息</h1>
        </el-row>
        <el-form ref="ruleForm" :model="form" :rules="rules" label-width="180px" size="medium">
          <el-row>
            <el-col :span="12">
              <el-form-item prop="instrumentNum">
                <template slot="label">
                  <span>仪器设备资产编号</span>
                  <el-tooltip class="item" effect="dark" content="暂未编制资产编号的，填写“暂无”" placement="top">
                    <i class="el-icon-question" style="color:#2c68ff" />
                  </el-tooltip>
                  <span>:</span>
                </template>
                <el-input v-model="form.instrumentNum" placeholder="请输入" :disabled="isFlag == 'look'" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="仪器设备（中文）名称：" prop="instrumentNameCn">
                <el-input v-model="form.instrumentNameCn" placeholder="请输入" :disabled="isFlag == 'look'" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="仪器设备（英文）名称：" prop="instrumentNameEn">
                <el-input v-model="form.instrumentNameEn" placeholder="请输入" :disabled="isFlag == 'look'" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="managementUnit">
                <template slot="label">
                  <span>管理单位</span>
                  <el-tooltip class="item" effect="dark" content="直接管理使用仪器设备的团级以上单位" placement="top">
                    <i class="el-icon-question" style="color:#2c68ff" />
                  </el-tooltip>
                  <span>:</span>
                </template>
                <el-input v-model="form.managementUnit" placeholder="请输入" :disabled="isFlag == 'look'" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="仪器设备来源：" prop="type">
                <el-radio-group v-model="form.type" :disabled="isFlag == 'look'">
                  <el-radio v-for="(item, index) in instrumentSource" :key="index" :label="item">{{ item }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="仪器设备分类：" prop="instrumentClassifyNum">
                <el-select style="width: 100%;" v-model="form.instrumentClassifyNum" :disabled="isFlag == 'look'">
                  <el-option v-for="item in instrumentNum" :label="item" :value="item" :key="item"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="产地国别：" prop="originCountry">
                <el-select style="width: 100%;" v-model="form.originCountry" :disabled="isFlag == 'look'">
                  <el-option v-for="item in nationality" :label="item" :value="item" :key="item"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生产厂商：" prop="manufacturer">
                <el-input v-model="form.manufacturer" placeholder="请输入" :disabled="isFlag == 'look'" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="规格型号：" prop="specifications">
                <el-input v-model="form.specifications" placeholder="请输入" :disabled="isFlag == 'look'" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="原值(万元)：" prop="originValue">
                <el-input v-model="form.originValue" oninput="value=value.replace(/[^0-9.]/g,'')" class="" placeholder="请输入"
                  :disabled="isFlag == 'look'">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="所属科研设施：" prop="belongFacilities">
                <el-select style="width: 100%;" v-model="form.belongFacilities" :disabled="isLook">
                  <el-option v-for="item in facilitiesLists" :label="item.facilityNameCn" :value="item.facilityNameCn"
                    :key="item.facilityNameCn"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="启用日期：" prop="yearStr">
                <el-date-picker style="width:100%" v-model="form.yearStr" type="date" value-format="yyyy-MM-dd" placeholder="选择日期"
                  :disabled="isFlag == 'look'">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="学科领域：" prop="disciplineField">
                <el-select style="width: 100%;" v-model="form.disciplineField" multiple :disabled="isLook">
                  <el-option v-for="item in subjectArea" :label="item" :value="item" :key="item"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="共享范围：" prop="sharedScope">
                <el-radio-group v-model="form.sharedScope" :disabled="isFlag == 'look'">
                  <el-radio class="p-b-10" v-for="(item, index) in shareScope" :key="index" :label="item">{{ item }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item class="jsonItem">
                <template slot="label">
                  <span>安放地址</span>
                  <el-tooltip class="item" effect="dark" content="设施所在的详细地理位置，标准格式：省、市、区(县)、街道(乡镇，需包括街道/乡镇门牌号)" placement="top">
                    <i class="el-icon-question" style="color:#2c68ff" />
                  </el-tooltip>
                  <span>:</span>
                </template>
                <el-form-item label="所属省：" prop="province" label-width="90px">
                  <el-select v-model="form.province" placeholder="请选择省">
                    <el-option v-for="item in provinces" :key="item.regionName" :label="item.regionName" :value="item.regionName" />
                  </el-select>
                </el-form-item>
                <el-form-item label=" 所属市：" prop="city" label-width="90px">
                  <el-select v-model="form.city" placeholder="请选择市区">
                    <el-option v-for="item in citys" :key="item.regionName" :label="item.regionName" :value="item.regionName" />
                  </el-select>
                </el-form-item>
                <el-form-item label=" 所属区：" prop="area" label-width="90px">
                  <el-select v-model="form.area" placeholder="请选择区域">
                    <el-option v-for="item in regions" :key="item.regionName" :label="item.regionName" :value="item.regionName" />
                  </el-select>
                </el-form-item>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="主要功能：" prop="majorFunction">
                <el-input v-model="form.majorFunction" placeholder="请输入" type="textarea" rows="4" :disabled="isFlag == 'look'" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="主要技术指标：" prop="technicalIndicators">
                <el-input v-model="form.technicalIndicators" placeholder="请输入" type="textarea" rows="4" :disabled="isFlag == 'look'" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="仪器设备图片：" prop="fileImgList">
                <el-upload action="#" list-type="picture-card" :on-change="handleChangeImg" :auto-upload="false" :file-list="form.fileImgList"
                  :disabled="isFlag == 'look'">
                  <i slot="default" class="el-icon-plus"></i>
                  <div slot="file" slot-scope="{file}" style="width:100%;height: 100%;">
                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                    <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-preview" @click="handlePictureImgPreview(file)">
                        <i class="el-icon-zoom-in"></i>
                      </span>
                      <span class="el-upload-list__item-delete" @click="handleRemoveImg(file)">
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </div>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible" title="预览" top="5vh">
                  <div style="width: 100%;height: 100%;text-align: center;">
                    <img width="70%" height="70%" :src="dialogImageUrl" alt="">
                  </div>
                </el-dialog>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="资料文档：" prop="fileList">
                <el-upload class="upload-demo" action="#" :on-change="handleChangeFile" :auto-upload="false" multiple :file-list="form.fileList"
                  :on-preview="handlePreviewFile" :on-remove="handleRemoveFile" :disabled="isFlag == 'look'">
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="p-b">
            <h1 class="before">服务信息</h1>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="服务内容：" prop="serviceContent">
                <el-input v-model="form.serviceContent" placeholder="请输入" type="textarea" rows="4" :disabled="isFlag == 'look'" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="p-b">
            <h1 class="before">服务要求</h1>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="申请条件：" prop="applicationConditions">
                <el-input v-model="form.applicationConditions" placeholder="请输入" :disabled="isFlag == 'look'" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请方式：" prop="applicationMethod">
                <el-input v-model="form.applicationMethod" placeholder="请输入" :disabled="isFlag == 'look'" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="申请时间：" prop="applicationTime">
                <el-input v-model="form.applicationTime" placeholder="请输入" :disabled="isFlag == 'look'" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请流程：" prop="applicationProcess">
                <el-input v-model="form.applicationProcess" placeholder="请输入" :disabled="isFlag == 'look'" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="申请材料：" prop="applicationMaterials">
                <el-input v-model="form.applicationMaterials" placeholder="请输入" :disabled="isFlag == 'look'" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="服务时间安排：" prop="serviceScheduling">
                <el-input v-model="form.serviceScheduling" placeholder="请输入" :disabled="isFlag == 'look'" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="收费标准：" prop="feeStandards">
                <el-input v-model="form.feeStandards" placeholder="请输入" type="textarea" rows="4" :disabled="isFlag == 'look'" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item prop="contacts">
                <template slot="label">
                  <span>联系人</span>
                  <el-tooltip class="item" effect="dark" content="设施仪器管理员" placement="top">
                    <i class="el-icon-question" style="color:#2c68ff" />
                  </el-tooltip>
                  <span>:</span>
                </template>
                <el-input v-model="form.contacts" placeholder="请输入" :disabled="isFlag == 'look'" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="办公电话：" prop="officePhoneNumber">
                <el-input v-model="form.officePhoneNumber" placeholder="请输入" :disabled="isFlag == 'look'" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="移动电话：" prop="mobileTelephone">
                <el-input v-model="form.mobileTelephone" placeholder="请输入" :disabled="isFlag == 'look'" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="通讯地址：" prop="mailingAddress">
                <el-input v-model="form.mailingAddress" placeholder="请输入" :disabled="isFlag == 'look'" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <PreviewPdf v-if="showPdf" :pdfUrl="pdfUrl" @closeLookPdf="closeLookPdf" />
  </div>
</template>

<script>
import {
  getFacilitiesList
} from '@/api/yqgx/facilities'
import {
  addInstrument,
  getInstrumentById,
  // getFacilitiesList
  updateInstrument,
} from '@/api/yqgx/instrument'
import { uploadFile, deleteFile } from '@/api/yqgx/uploadFile'
import PreviewPdf from '@/views/common/previewPdf.vue'
export default {
  components: { PreviewPdf },
  computed: {
    isFlag() {
      return this.$route.params.flag
    },
    isAudit() {
      return this.$route?.params?.isAudit ?? false
    },
    rowId() {
      return this.$route.params.id
    },
    userAuth() {
      return localStorage.getItem('userInfo')
        ? JSON.parse(localStorage.getItem('userInfo'))[0]
        : {
          "userId": 1299,
          "userName": "admin",
          "userRealName": "管理员",
          "userEmail": null,
          "deptName": null,
          "createBy": "admin",
          "createTime": "2024-01-02 21:39:11",
          "departmentName": "",
          "departmentId": null,
          "selectFlag": true,
          "userHeadPath": null,
          "userPhone": 18702348729,
          "enableFlag": "y",
          "roleName": "平台管理员"
        }
    },
    regionJson() {
      return localStorage.getItem('newRegion')
        ? JSON.parse(localStorage.getItem('newRegion'))
        : {}
    },

  },
  data() {
    return {
      provinces: [],
      citys: [],
      regions: [],
      isLook: false,
      dialogImageUrl: '',
      dialogVisible: false,
      showPdf: false,
      pdfUrl: null,
      title: '',
      accept: '.doc,.docx,.pdf',
      form: {
        instrumentNum: '',
        instrumentNameCn: '',
        instrumentNameEn: '',
        managementUnit: '',
        type: '购置',
        instrumentClassifyNum: '',
        originCountry: '',
        manufacturer: '',
        specifications: '',
        originValue: '',
        belongFacilities: '',
        yearStr: '',
        disciplineField: '',
        sharedScope: '',
        placementAddress: '',
        majorFunction: '',
        technicalIndicators: '',
        fileImgList: [],
        fileList: [],
        serviceContent: '',
        applicationConditions: '',
        applicationMethod: '',
        applicationTime: '',
        applicationProcess: '',
        applicationMaterials: '',
        serviceScheduling: '',
        feeStandards: '',
        contacts: '',
        officePhoneNumber: '',
        mobileTelephone: '',
        mailingAddress: '',
        // 发布状态
        releaseStatus: '未发布',
      },
      rules: {
        instrumentNum: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        instrumentNameCn: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        instrumentNameEn: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        managementUnit: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        type: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        instrumentClassifyNum: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        originCountry: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        manufacturer: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        specifications: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        originValue: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        belongFacilities: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        yearStr: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        disciplineField: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        sharedScope: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        // placementAddress: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        majorFunction: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        technicalIndicators: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        // serviceContent: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        // applicationConditions: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        // applicationMethod: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        // applicationTime: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        // applicationProcess: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        // applicationMaterials: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        // serviceScheduling: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        // feeStandards: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        // contacts: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        // mobileTelephone: [{ required: true, message: '不能为空！', trigger: 'blur' }],
      },
      instrumentSource: JSON.parse(localStorage.getItem('dictLists'))
        .instrumentSource,
      subjectArea: JSON.parse(localStorage.getItem('dictLists')).subjectArea,
      shareScope: JSON.parse(localStorage.getItem('dictLists')).shareScope,
      instrumentNum: JSON.parse(localStorage.getItem('dictLists'))
        .instrumentNum,
      nationality: JSON.parse(localStorage.getItem('dictLists')).nationality,
      queryParams: {
        total: 0,
        currentPage: 1,
        pageSize: 10
      },
      facilitiesLists: []
    }
  },
  created() {
    this.provinces = this.regionJson.province
    switch (this.isFlag) {
      case 'add':
        this.title = '新增仪器设备'
        this.form.contacts = this.userAuth.userRealName
        this.form.managementUnit = this.userAuth.departmentName
        this.form.mobileTelephone = this.userAuth.userPhone
        break
      case 'edit':
        this.title = '修改仪器设备'
        this.getDetail()
        break
      case 'look':
        this.title = '查看仪器设备'
        this.getDetail()
        break
    }
    getFacilitiesList().then((res) => {
      this.facilitiesLists = res.data
    })
  },
  watch: {
    'queryString.itemName'(newValue) {
      this.tableData = this.allTableData.filter(
        item => item.itemName.indexOf(newValue) > -1
      )
    },
    'queryString.domainName'(newValue) {
      this.tableData = this.allTableData.filter(
        item => item.domainName.indexOf(newValue) > -1
      )
    },

    "form.province"(newVal, oldVal) {
      if (newVal && oldVal != undefined) {
        // delete this.form.city;
        // delete this.form.area;
        this.$set(this.form, "city", "");
        this.$set(this.form, "area", "");
        this.getLevelCity();
      } else {
        this.getLevelCity();
      }
    },
    "form.city"(newVal, oldVal) {
      if (newVal && oldVal != undefined) {
        // delete this.form.area;
        this.$set(this.form, "area", "");
        this.getLevelRegion();
      } else {
        this.getLevelRegion();
      }
    },
    deep: true
  },
  mounted() { },
  methods: {
    downloadLink(item) {
      this.downloadByUrl(item.fileName, item.filePath)
    },
    lookPdf(url) {
      this.pdfUrl = url
      this.showPdf = true
    },
    closeLookPdf() {
      this.showPdf = false
      this.pdfUrl = null
    },
    getDetail() {
      getInstrumentById(this.rowId).then(res => {
        let _res = res.data
        let arr = res.data.placementAddress.split(';')
        this.$nextTick(() => {
          _res.province = arr[0]
          _res.city = arr[1]
          _res.area = arr[2]
          this.form = _res
        })
      })
    },
    goBack() {
      this.$router.go(-1)
    },
    auditMethed() {
      this.form.Report = '待上报'
      updateInstrument(this.form).then(() => {
        this.goBack()
      }).catch((err) => {
        console.log(err, 'err');
      })
    },
    auditNoMethed() {
      this.form.Report = '审核未通过'
      updateInstrument(this.form).then(() => {
        this.goBack()
      }).catch((err) => {
        console.log(err, 'err');
      })
    },
    submitForm() {
      let that = this
      this.form.placementAddress = `${this.form.province};${this.form.city};${this.form.area}`
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          let params = this.form
          if (this.isFlag == 'add') {
            addInstrument(params).then(() => {
              that.goBack()
            }).catch((err) => {
              console.log(err, 'err');
            })
          } else if (this.isFlag == 'edit') {
            updateInstrument(params).then(() => {
              that.goBack()
            }).catch((err) => {
              console.log(err, 'err');
            })
          }
        } else {
          return false
        }
      })
    },
    getLevelCity() {
      this.citys = this.regionJson.city[this.form.province];
    },
    getLevelRegion() {
      this.regions = this.regionJson.area[this.form.city];
      console.log('%c [ this.regions ]-583', 'font-size:13px; background:pink; color:#bf2c9f;', this.regions)
    },
    // 下载模板
    download() {
      // downloadTemplate()
    },
    // 上传文件
    handleChangeImg(file) {
      let baseURL = process.env.VUE_APP_BASE_API + "/"
      const _file = file?.raw ?? file
      const formData = new FormData()
      formData.append('file', _file)
      formData.append('pathType', file.name.split('.').pop())
      uploadFile(formData).then((res) => {
        this.form.fileImgList.push({
          uid: file.uid,
          filename: res.filename,
          url: baseURL + res.filename
        })
      })
    },
    // 文件删除
    handleRemoveImg(file) {
      const index = this.form.fileImgList.findIndex(function (val) {
        return val.filename === file.filename
      })
      let deleteItem = this.form.fileImgList[index]
      this.form.fileImgList.splice(index, 1)
      deleteFile(deleteItem.filename)
      this.$message.success('删除成功！')
    },
    // 文件查看
    handlePictureImgPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 材料上传
    handleChangeFile(file) {
      let baseURL = process.env.VUE_APP_BASE_API + "/"
      const _file = file?.raw ?? file
      const formData = new FormData()
      formData.append('file', _file)
      formData.append('pathType', file.name.split('.').pop())
      uploadFile(formData).then(res => {
        this.form.fileList.push({
          uid: file.uid,
          name: file.name,
          filename: res.filename,
          url: baseURL + res.filename
        })
      })
    },
    // 文件删除
    handleRemoveFile(file) {
      const index = this.form.fileList.findIndex(function (val) {
        return val.filename === file.filename
      })
      let deleteItem = this.form.fileList[index]
      this.form.fileList.splice(index, 1)
      deleteFile(deleteItem.filename)
      this.$message.success('删除成功！')
    },
    // 文件查看
    handlePreviewFile() { },
    deleteFun(row) {
      let itemIndex = this.tableData.findIndex(function (obj) {
        return row === obj
      })
      // this.tableData.splice(itemIndex, 1)
      this.allTableData.splice(itemIndex, 1)
    }
  }
}
</script>

<style lang="less" scoped>
  ::v-deep.flex-rowform {
    .el-form-item__content {
      display: flex;
    }

    .r-span {
      display: inline-block;
      width: 100px;
      line-height: 40px;
    }
  }

  .info-box {
    position: relative;
  }

  .header {
    position: fixed;
    width: 100%;
    display: flex;
    align-items: center;
    z-index: 9;
    padding: 16px 20px;
    margin-top: 2px;

    .saveBtn {
      position: fixed;
      z-index: 10;
      right: 50px;
    }
  }
  ::v-deep(.jsonItem) {
    .el-form-item__content {
      display: flex;
      align-items: center;
    }
  }

  .form-content {
    padding-top: 90px;
  }
</style>